//加载express
const express = require('express')

const router = express.Router();

const {
    user
} = require('../model/db')

//**************星号内部写API接口******************* */ 

// 获取openid
// req是获取小程序端发过来的数据，res是向小程序返回数据
router.get('/wxlogin', async (req, res) => {
    // console.log(req.query)
    const {
        code
    } = req.query
    const appID = "wx45ae1e9b07e371a4"
    const AppSecret = "1ab1044500e812dc8cdc0f7176980344"
    //访问微信服务器，需要使用request框架，打开新控制台 输入 npm install request --save 下载 
    const request = require('request')
    request({
            url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`
        },
        (err, response, data) => {
            if (!err && response.statusCode == 200) {
                // console.log(typeof(data)) 
                // console.log(data)
                res.send({
                    status: 'ok',
                    openid: JSON.parse(data).openid
                });
            } else {
                console.log(err);
                res.send({
                    status: 'err',
                    errMsg: err
                })
            }
        });
})
// 获取用户信息 小程序
router.post('/wxGetUserInfo', async (req, res) => {
        // console.log(req.body)
        const {
            userInfo
        } = req.body
        const result = await user.findOne({
            openid: userInfo.openid
        }).select('-_id')
        // console.log(result)
        try {
            if (result) { //数据库中存在用户
                res.send({
                    status: 'ok',
                    value: result
                })

            } else { //新用户需要存入数据库
                const res1 = await user.create(userInfo)
                // console.log(res)
                res.send({
                    status: 'ok',
                    value: userInfo
                })
            }
        } catch (error) {
            console.log(error)
            res.send({
                status: 'err'
            })
        }
    }

)

//导入multer 
const multer = require('multer')
//上传参数设置 
const storage = multer.diskStorage({
    //配置路径,首先需要创建uploads/images文件夹 
    destination: (req, file, cb) => {
        cb(null, './uploads/images');
    },
    //设置文件名 
    filename: (req, file, cb) => {
        let extName = '.' + file.originalname.split('.').pop();
        let fileName = Date.now() + Math.floor(Math.random() * 10000);
        cb(null, fileName + extName);
    }
})
//应用上传设置，并实例上传对象 
const upload = multer({
    storage: storage
})
//头像图片上传 
router.post('/uploadImg', upload.single('img'), (req, res) => {
    try {
        res.send(req.file);
    } catch (error) {
        res.send(error);
        console.log(error)
    }
})

//userRouter.js 小程序端 修改用户信息 
router.post('/wxUpdateUserInfo', async (req, res) => {
    try {
        const {
            openid
        } = req.body
        const result = await user.findOneAndUpdate({
            openid
        }, req.body).select('-_id')
        res.send({
            status: 'success',
            result
        })
    } catch (error) {
        console.log(error)
        res.send({
            status: 'err'
        })
    }
})

//小程序端 申请成为接单员 
router.post('/wxApplyOrder', async (req, res) => {
    try {
        // console.log(req.body) 
        const {
            openid,
            personInfo
        } = req.body
        const result = await user.findOneAndUpdate({
            openid
        }, {
            personInfo
        })
        res.send('success')
    } catch (err) {
        console.log(err)
        res.send('fail')
    }
})

//小程序 读取用户申请接单信息 
router.get('/wxGetUser', async (req, res) => {
    try {
        const {
            openid
        } = req.query
        const result = await user.findOne({
            openid
        }).select("personInfo")
        res.send({
            status: 'success',
            result
        })
    } catch (error) {
        res.send({
            status: 'fail'
        })
    }
})
//小程序 管理员读取所有用户接单申请 
router.get('/wxGetAllApply', async (req, res) => {
    try {
        const {
            page,
            pageSizes
        } = req.query;
        const result = await user.find({
            personInfo: {
                $ne: null
            }
        }).select("personInfo").skip(page).limit(pageSizes).sort({
            "personInfo.applyT ime": -1
        });
        res.send(result)
    } catch (error) {
        res.send(error)
    }
})
//小程序 读取接单申请的记录数 
router.get('/wxApplyCount', async (req, res) => {
    try {
        const count = await user.countDocuments({
            personInfo: {
                $ne: null
            }
        });
        res.send({
            status: 'success',
            count
        })
    } catch (error) {
        res.send({
            status: 'error'
        })
    }
})
//小程序 审核接单申请 
router.post('/wxApplyVerify', async (req, res) => {
    try {
        //console.log(req.body) 
        const {_id,status} = req.body
        if (status === "通过审核") {
            await user.findByIdAndUpdate(_id, {canReceive: true,"personInfo.status": status})
        } else {
            await user.findByIdAndUpdate(_id, {"personInfo.status": status})
        }
        res.send('success')
    } catch (error) {
        console.log(error)
        res.send('fail')
    }
})

//************************************************* */ 
//导出路由 
module.exports = router;